package com.wangyadong.hobby.admin.servcie.impl;

import com.wangyadong.hobby.admin.servcie.IAnswerService;
import com.wangyadong.hobby.common.constants.RedisKeyConstants;
import com.wangyadong.hobby.common.question.Answer;
import com.wangyadong.hobby.common.utils.UniqueIDUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;

import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import static com.wangyadong.hobby.common.utils.MapObjectConvert.maptoObject;
import static com.wangyadong.hobby.common.utils.MapObjectConvert.objectToMap;

@Component
public class AnswerServiceImpl implements IAnswerService {

    Jedis conn = new Jedis("127.0.0.1");

    @Override
    public int saveOrUpdateAnswer(Answer answer) throws Exception {
        if (!StringUtils.isBlank(answer.getId())) {
            answer.setId(UniqueIDUtil.getUniqueID() + "");
        }
        long now = System.nanoTime() / 1000;
        String key = RedisKeyConstants.ANSWER.getCode() + answer.getId();
        conn.hmset(key, objectToMap(answer));
        return 0;
    }

    /***
     *
     * @param questionId
     * @return
     */
    @Override
    public int deleteAnswer(Long questionId) {
        String key = RedisKeyConstants.ANSWER.getCode() + questionId;
        Map<String, String> map = conn.hgetAll(key);
        Set<String> keys = map.keySet();
        String[] strings = new String[keys.size()];
        Iterator<String> iterator = keys.iterator();
        int i = 0;
        while (iterator.hasNext()) {
            String next = iterator.next();
            strings[i] = next;
            i++;
        }
        Long result = conn.hdel(key, strings);
        return result.intValue();
    }

    @Override
    public Answer getAnswerDetail(Long questionId) throws InstantiationException, IllegalAccessException {
        String key = RedisKeyConstants.ANSWER.getCode() + questionId;
        return (Answer) maptoObject(conn.hgetAll(key), Answer.class);
    }
}
